﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using GameBase;
using GameBase.Form.Control;

namespace GalaxyPresident
{
    public class PlanetLayer : PlayScreenLayer
    {
        private Planet _planet;
        
        ConstructionTask currentConstruction;
        List<DetailPlanetView> objectViews;
        PlanetEntity focusedEntity;
        PlanetEntity hoverEntity;
        public void SetConstruction(ConstructionTask construction)
        {
            _playingScreen.InfoPanel.Visible = false;
            focusedEntity = null;
            if (currentConstruction != null)
            {
                layer.RemoveChild(currentConstruction.GetDrawingObject());
            }
            currentConstruction = construction;
            layer.AddChild(currentConstruction.GetDrawingObject());
        }
        public void CancelBuildingHouse()
        {
            if (currentConstruction != null)
            {
                if (currentConstruction.GetType() == typeof(Capital))
                {
                    Planet.TeamOwner = null;
                }

                layer.RemoveChild(currentConstruction.GetDrawingObject());
                currentConstruction = null;
            }
        }
        public Planet Planet
        {
            get { return _planet; }
            set { _planet = value; }
        }

        public PlanetLayer(PlayingScreen playingScreen,Planet planet)
            : base(playingScreen)
        {
            Layer = new VisibleGroup();
            Vector2 center = new Vector2(Constant.screenWidth, Constant.screenHeight) / 2;
            Position = center;
            topLeft = new Vector2(-800, -1000);
            bottomRight = new Vector2(800, 1000);

            SetPlanet(planet);
            AddChild(Layer);
            //lastMouseState = Mouse.GetState();
            minScale = 0.4f;
            maxScale = 1.5f;

           /*=============================
            *      Only for test          
            *=============================*/
            //barrack = new Barrack(_planet);
            //_planet.TeamOwner = _teams[0];
        }

        public void SetPlanet(Planet planet)
        {
            this.Planet = planet;
            Layer.RemoveAllChild();
            VisibleObject halo = new VisibleObject(@"Resources/halo", 1, 1);
            halo.Depth = 1f;
            halo.Scale = planet.Diameter/10;
            halo.Sprite.SetOriginPosition(ORIGIN_POSITION.Center);
            halo.Color = planet.AtmospherColor;
            Layer.AddChild(halo);
            objectViews = new List<DetailPlanetView>();
            Layer.AddChild(planet.ViewLayer);
            objectViews.Add(planet.ViewLayer);
            foreach (Moon moon in planet.Moons)
            {
                Layer.AddChild(moon.ViewLayer);
                objectViews.Add(moon.ViewLayer);
            }


            //lastMouseState = Mouse.GetState();
            Scale = 0.3f;
            TargetScale = 1f;
            Layer.Position = Vector2.Zero;

           /* foreach (Unit unit in planet.Units)
                AddChild(unit);*/
        }


        /*=============================
         *      Only for test          
         *=============================*/
        //bool iskeydown1 = false;
        //bool iskeydown2 = false;
        //bool iskeydown3 = false;
        //AirPort barrack;
        
        public override void HandleKeyBoard()
        {/*
            KeyboardState kbs = Keyboard.GetState();
            if (kbs.IsKeyDown(Keys.D1))
                iskeydown1 = true;
            if (kbs.IsKeyUp(Keys.D1) && iskeydown1)
            {
                iskeydown1 = false;
                Unit unit = barrack.createUnit(0);
                
                if (unit != null)
                {
                    Planet.AddUnit(unit);
                }
            }


            if (kbs.IsKeyDown(Keys.D2))
                iskeydown2 = true;
            if (kbs.IsKeyUp(Keys.D2) && iskeydown2)
            {
                iskeydown2 = false;
                Unit unit = barrack.createUnit(1);
                if (unit != null)
                {
                    Planet.AddUnit(unit);
                }
            }


            if (kbs.IsKeyDown(Keys.D3))
                iskeydown3 = true;
            if (kbs.IsKeyUp(Keys.D3) && iskeydown3)
            {
                iskeydown3 = false;
                Unit unit = barrack.createUnit(2);
                if (unit != null)
                {
                    Planet.AddUnit(unit);
                }
            }*/
        }

        bool isLeftClick = false;
        bool isRightClick = false;
        //bool isDrag = false;
        bool isFirstPress = true;
        Vector2 lastPressPos;
        public override void MousePressed(bool onForm)
        {
            base.MousePressed(onForm);
            if (IsMouseMoved())
                return;
            if (currentConstruction == null && !onForm)
            {
                /*focusedEntity = GetPlanetEntityAtMouse();
                if (focusedEntity != null)
                {
                  //  _playingScreen.InfoPanel.SetEntity(focusedEntity);
                   // _playingScreen.InfoPanel.Visible = true;
                }*/
                //else
                //{
                    _playingScreen.InfoPanel.Visible = false;
                    focusedEntity = null;
                //}
            }
            else if (currentConstruction != null && onForm)
            {
                CancelBuildingHouse();
            }
        }
        public override void MouseReleased(bool onForm)
        {
            base.MouseReleased(onForm);
            if (IsMouseMoved())
                return;
            if (currentConstruction == null)
            {
                if (!onForm)
                {
                    focusedEntity = GetPlanetEntityAtMouse();
                    if (focusedEntity != null)
                    {
                        _playingScreen.InfoPanel.SetEntity(focusedEntity);

                        if(Planet.TeamOwner == _teams[0])
                            _playingScreen.InfoPanel.Visible = true;
                    }
                }
            }
            else
            {
                if (currentConstruction.Execute())
                {
                    CancelBuildingHouse();
                }
            }
        }

        private PlanetEntity GetPlanetEntityAtMouse()
        {
                Rectangle bound = new Rectangle((int)(-Constant.sizeBlock),
                    (int)(-Constant.sizeBlock*4),
                    (int)Constant.sizeBlock*2,(int)Constant.sizeBlock*4);
                Vector2 mousePos = new Vector2(MouseState.X,MouseState.Y);
            foreach (DetailPlanetView obj in objectViews)
            {
                for (int i = 0; i < obj.Planet.BlockCount; i++)
                {
                    PlanetEntity entity = obj.Planet.Blocks[i].Entity;
                    if (entity != null)
                    {
                        Vector2 pos = entity.GetLocalPosition(mousePos);
                        if(entity.IsHover(pos.X,pos.Y,bound))
                        {
                            return entity;
                        }
                    }
                }
            }
            
            return null;
        }
        public PlanetObjectOwner GetPlanetObjectOwnerAtMouse()
        {
            foreach(VisibleGameEntity obj in Planet.ViewLayer.ListChildren)
            {
                if (obj is PlanetObjectOwner)
                {
                    if ((obj.GetDrawPosition() -
                        new Vector2(MouseState.X, MouseState.Y)).Length() < 80)
                    {
                        return (PlanetObjectOwner)obj;
                    }
                }
            }
            return null;
        }
        public override void MouseHandle()
        {
            base.MouseHandle();
            
            MouseState ms = Mouse.GetState();
            Vector2 mousePos = new Vector2(ms.X, ms.Y);

            if (ms.LeftButton == ButtonState.Pressed)
            {
                isLeftClick = true;
                if (isFirstPress)
                {
                    isFirstPress = false;
                    lastPressPos = mousePos;
                    focusedEntity = null;
                }
            }
            if (ms.RightButton == ButtonState.Pressed && isRightClick)
            {
                isRightClick = true;

                if (isFirstPress)
                {
                    CancelBuildingHouse();

                    isFirstPress = false;
                    lastPressPos = mousePos;
                }
            }

            //if ((isLeftClick || isRightClick) && (lastPressPos != mousePos))
            //    isDrag = true;
            //else
            //    isDrag = false;

            if (ms.LeftButton == ButtonState.Released && isLeftClick)
            {
            }
            if (MouseState.RightButton == ButtonState.Released && 
                LastMouseState.RightButton == ButtonState.Pressed)
            {
                PlanetObjectOwner target = GetPlanetObjectOwnerAtMouse();
                if(target == null)
                {
                    return;
                }
                List<MotherShip> motherShips = _playingScreen.Teams[0].getAllMotherShipAtPlanet(Planet);
                foreach (MotherShip mship in motherShips)
                {
                    mship.Attack(target);
                }
            }
        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (currentConstruction == null)
            {
                hoverEntity = GetPlanetEntityAtMouse();
                if (focusedEntity != null)
                {
                    Vector2 target = -layer.GetLocalPosition(focusedEntity.GetDrawPosition());
                    Vector2 newPos = MotionEffects.Move(layer.Position, target,30);
                    layer.Position = newPos;
                }
            }
            else
            {
                SnapBuildingConstruction();
            }
        }

        private void SnapBuildingConstruction()
        {
            Vector2 mousePosition = layer.GetLocalPosition(new Vector2(MouseState.X, MouseState.Y));

            bool isSnaped = false;
            float min = 80;
            Vector2 buildPosition = Vector2.Zero;
            float buildRotate = 0;
            currentConstruction.Planet = null;
            foreach (DetailPlanetView obj in objectViews)
            {
                for (int i = 0; i < obj.Planet.BlockCount; i++)
                {
                    Vector2 blockPosition = obj.Planet.GetBlockPosition(i) +
                        obj.Position;
                    float d = (blockPosition - mousePosition).Length();
                    if (currentConstruction.IsAvailable(obj.Planet.IsEmptyBlock(i)) &&
                        d < min)
                    {
                        min = d;
                        isSnaped = true;
                        buildPosition = blockPosition;
                        buildRotate = obj.Planet.GetBlockRotation(i);
                        currentConstruction.Planet = obj.Planet;
                        currentConstruction.BlockIndex = i;
                    }
                }
            }

            if (isSnaped)
            {
                currentConstruction.GetDrawingObject().Position = buildPosition;
                currentConstruction.GetDrawingObject().Rotate = buildRotate;
            }
            else
            {
                currentConstruction.GetDrawingObject().Position = mousePosition;
                currentConstruction.GetDrawingObject().Rotate = 0;
            }
        }

        public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            base.Draw(gameTime, spriteBatch);

            if (_planet.TeamOwner != null && _planet.TeamOwner == _teams[0])
            {
                string planetResStr = "Material: " + ((int)(_planet.Meterial)).ToString()
                                  + "\nEnergy  : " + ((int)(_planet.Energy)).ToString()
                                  + "\nMoney   : " + ((int)(_planet.TeamOwner.TotalMoney)).ToString();
                Text.Draw(spriteBatch, planetResStr, Constant.fontNormalBold, 20 * _playingScreen.Form.ScreenScale.X, 70 * _playingScreen.Form.ScreenScale.Y,PlayingScreen.FORCOLOR);
            }

            //if (_planet.TeamOwner != null)
            //{
            //    string planetResStr = "Material: " + ((int)(_planet.Meterial)).ToString()
            //                      + "\nEnergy  : " + ((int)(_planet.Energy)).ToString()
            //                      + "\nMoney   : " + ((int)(_planet.TeamOwner.TotalMoney)).ToString();

                //Text.Draw(spriteBatch, @"Material: ",Constant.fontSmallBold,20,45);
                //Text.Draw(spriteBatch, @"Energy  : ", Constant.fontSmallBold, 20, 65);
                //Text.Draw(spriteBatch, @"Money   : ", Constant.fontSmallBold, 20, 85);

                //Text.Draw(spriteBatch, ((int)(_planet.Meterial)).ToString(), Constant.fontNormalBold, 140, 45);
                //Text.Draw(spriteBatch, ((int)(_planet.Energy)).ToString(), Constant.fontNormalBold, 140, 65);
                //Text.Draw(spriteBatch, ((int)(_planet.TeamOwner.TotalMoney)).ToString(), Constant.fontNormalBold, 140, 85);

            //}
            if (hoverEntity != null)
            {
                Vector2 drawPosition = hoverEntity.GetDrawPosition();
                Text.Draw(spriteBatch, hoverEntity.getObjectName(), Constant.fontNormalBold,
                    MouseState.X, MouseState.Y-30, Color.White, Color.Black);   
            }
            /*
            Text.Draw(spriteBatch, "DEBUG AREA", Constant.fontNormalBold, 400, 40);
            if (focusedEntity != null)
            {
                Text.Draw(spriteBatch,"FOCUS", Constant.fontNormalBold, 400, 60);
            }
            
            Text.Draw(spriteBatch, MouseState.LeftButton.ToString(),
                    Constant.fontNormalBold, 400, 80);
            
            if (mousePressed)
            {
                Text.Draw(spriteBatch, "PRESSED", Constant.fontNormalBold, 500, 80);
            }*/
        }

        public void setNoFucusEntity()
        {
            focusedEntity = null;
        }
    }
}
